package com.yuyuan.wxmp.controller;

import com.yuyuan.wxmp.common.ErrorCode;
import com.yuyuan.wxmp.exception.ThrowUtils;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.web.bind.annotation.*;

/**
 * 微信消息接收接口
 */
@RestController
@RequestMapping("/wx/msg/{appId}")
@RequiredArgsConstructor
@Slf4j
public class WxMpPortalController {

    private final WxMpService wxService;
    private final WxMpMessageRouter messageRouter;

    // 服务器认证接口（GET请求）已在之前章节实现，此处略过...

    /**
     * 处理微信服务器发来的各类消息
     */
    @PostMapping(produces = "application/xml; charset=UTF-8")
    @Operation(summary = "微信各类消息", description = "公众号接入开发模式后才有效")
    public String post(@PathVariable String appId,
                       @RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {
        // 切换到对应公众号的配置
        this.wxService.switchoverTo(appId);

        // 验证请求签名
        ThrowUtils.throwIf(!wxService.checkSignature(timestamp, nonce, signature),
                ErrorCode.PARAMS_ERROR, "非法请求，可能属于伪造的请求！");

        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            WxMpXmlOutMessage outMessage = this.route(appId, inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxService.getWxMpConfigStorage(),
                    timestamp, nonce, msgSignature);
            log.info("消息解密后内容为：\n{} ", inMessage.toString());
            WxMpXmlOutMessage outMessage = this.route(appId, inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toEncryptedXml(wxService.getWxMpConfigStorage());
        }

        log.info("组装回复信息：{}", out);
        return out;
    }

    /**
     * 路由消息到对应的处理器
     */
    private WxMpXmlOutMessage route(String appid, WxMpXmlMessage message) {
        try {
            return messageRouter.route(appid, message);
        } catch (Exception e) {
            log.error("路由消息时出现异常！", e);
        }
        return null;
    }
}
